<template>
<div :class="[$style.container]">
  <el-input v-model="text" type="textarea" size="mini" maxlength="200" :row="1" show-word-limit
    :autosize="autoSize" placeholder="请输入评论" ref="input" @blur="onBlur"></el-input>
  <div :class="[$style.action]">
    <!-- <el-button type="text" size="mini" :disabled="sending">提醒@</el-button> -->
    <div>
      <el-button type="text" size="mini" :disabled="sending" @click="onCancel" v-if="expand"><span class="text-secondary">取消</span></el-button>
      <el-button type="text" size="mini" :loading="sending" @click="onSend" v-if="expand">发送</el-button>
    </div>
  </div>
</div>
</template>

<script lang="ts">

import { PageData } from '@/config/page'
import { Vue, Component, Provide, Watch, Ref, Prop } from 'vue-property-decorator'

@Component
export default class MessageInput extends Vue {
  @Prop() sendFn!: (context: any, text: string) => Promise<any>

  @Ref() input: any

  text = ''

  context: any = null

  sending = false

  tip = ''

  get expand () {
    return !!this.text || !!this.text.trim()
  }

  get autoSize () {
    if (this.expand) {
      return { minRows: 3, maxRows: 3 }
    }
    return { minRows: 1, maxRows: 1 }
  }

  onCancel () {
    this.text = ''
    this.context = null
    this.tip = ''
  }

  open (context: any) {
    this.context = context || null
    const { comment, reply } = this.context || {}
    if (!reply) {
      this.tip = '回复 :'
    } else {
      this.tip = `回复 ${reply.replyByName} :`
    }
    this.text = this.tip
    if (this.input) this.input.focus()
  }

  onSend () {
    if (this.sendFn) {
      const ctx = this.context || { type: 'comment' }
      const text = this.text.replace(new RegExp(`^${this.tip}`), '')
      this.sending = true
      this.sendFn(ctx, text).then(() => {
        this.onCancel()
      }).catch(() => {
        // ignore
      }).finally(() => {
        this.sending = false
      })
    } else {
      this.onCancel()
    }
  }

  onBlur () {
    if (!this.text || !this.text.trim()) {
      this.onCancel()
    }
  }
}
</script>

<style lang="scss" module>
@import "~@/styles/vars.scss";

.container {

}

.action {
  display: flex;
  justify-content: space-between;
}
</style>
